﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Kokomo.PeInspector.ObjectGraphs
{
	class EnumerableTemplate<TElement> : ObjectTemplate<IEnumerable<TElement>>
	{
		public EnumerableTemplate(
			IEnumerable<ElementTemplate> elementTemplates = null,
			IEnumerable<MemberTemplate> memberTemplates = null
			)
			: base(memberTemplates)
		{
			this.ElementTemplates = new List<ElementTemplate>();
			if (elementTemplates != null) this.ElementTemplates.AddRange(elementTemplates);
		}

		public List<ElementTemplate> ElementTemplates { get; private set; }

		public override bool Inspect(object value)
		{
			bool baseInspect = base.Inspect(value);
			if (!baseInspect) return false;

			IEnumerable<TElement> array = value as IEnumerable<TElement>;
			if (array == null) return false;

			bool matches = true;
			foreach (var elementTemplate in this.ElementTemplates)
			{
				matches &= elementTemplate.Inspect(array);
			}

			if (matches) this.CapturedValue = array;

			return matches;
		}
	}
}
